package com.fzg.common.tool;


import lombok.extern.slf4j.Slf4j;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


@Slf4j
public class StringUtilTool {

	/**
	 * 处理通过传递的字符串进行转换空格处理
	 */
	public static String convertStr(String strParam) {
		if (null == strParam) {
			strParam = "";
		} else {
			strParam = strParam.trim();
		}
		return strParam;
	}
	
	/**
	 * 将传入的对象转为字符串
	 * @param strParam 参数：object对象
	 * @return String
	 */
	public static String convertStr(Object strParam) {
		String result;
		if (null == strParam) {
			result = "";
		} else {
			result = String.valueOf(strParam).trim();
		}
		return result;
	}

	/**
	 * @description:  创建目录
	 * @param fileDir 目标目录名
	 * @return boolean
	 */
	public static boolean createDir(String fileDir) {
		boolean isDir;
		try {
			File folder = new File(fileDir);
			if (!(folder.exists() && folder.isDirectory())) {
				folder.mkdirs();
			}
			isDir = true;

		} catch (Exception e) {
			e.printStackTrace();
			isDir = false;
		}
		return isDir;
	}

	/**
	 * 将Zip压缩字节数组解压
	 * 
	 * @param zipBytes 参数：Zip字节数组
	 * @return 解压后的字节数组
	 * @throws IOException IO异常
	 */
	public static byte[] unzip(byte[] zipBytes) throws IOException {
		ByteArrayInputStream bais = new ByteArrayInputStream(zipBytes);
		ZipInputStream zis = new ZipInputStream(bais);
		zis.getNextEntry();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		final int BUFSIZ = 4096;
		byte[] inbuf = new byte[BUFSIZ];
		int n;
		while ((n = zis.read(inbuf, 0, BUFSIZ)) != -1) {
			baos.write(inbuf, 0, n);
		}
		byte[] data = baos.toByteArray();
		zis.close();
		return data;
	}

	/**
	 * 将字节数组Zip压缩
	 * 
	 * @param data 参数
	 * @return byte[]
	 * @throws IOException 异常
	 */
	public static byte[] zip(byte[] data) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ZipEntry ze = new ZipEntry("servletservice");
		ZipOutputStream zos = new ZipOutputStream(baos);
		zos.putNextEntry(ze);
		zos.write(data, 0, data.length);
		zos.close();
		byte[] zipBytes = baos.toByteArray();
		return zipBytes;
	}

	/**
	 * 对字符串先进行zip压缩，再进行base64编码
	 * 
	 * @param qrStr 参数
	 * @return String
	 * @throws IOException 异常
	 */
	public static String encode(String qrStr) throws IOException {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(zip(qrStr.getBytes(StandardCharsets.UTF_8)));
	}
	
	/**
	 * 
	 * @name:         encode
	 * @description: 将StringBuffer转换成UTF-8编码并用base64编码！
	 * @description: 不适合超长字符串处理
	 * @param qrStr  参数
	 * @return       String
	 * @throws IOException 异常
	 */
	public static String encode(StringBuffer qrStr) throws IOException {
		return encode(qrStr.toString());
	}

	/**
	 * 对字符串先进行base64解码，再进行zip解压
	 * 
	 * @param qrStr 参数
	 * @return String
	 * @throws IOException 异常
	 */
	public static String decode(String qrStr) throws IOException {
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] bytes = decoder.decodeBuffer(qrStr);
		String str = new String(unzip(bytes), StandardCharsets.UTF_8);//
		return str;
	}
	
	public static String decode(String qrStr,String decode) throws IOException {
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] bytes = decoder.decodeBuffer(qrStr);
		String str = new String(unzip(bytes), decode);//
//		WSXmlTraceUtil.log(str);
		return str;
	}

	/**
	 * 对DOC 文件输出xml字符串
	 * 
	 * @param doc 参数
	 * @return String
	 * @throws IOException 异常
	 */
	public static String docToXml(Document doc) throws IOException {
		Format format = Format.getPrettyFormat();
		format.setEncoding("UTF-8");// 设置xml文件的字符为UTF-8，解决中文问题
		XMLOutputter xmlout = new XMLOutputter(format);
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		xmlout.output(doc, bo);
		String xmlStr = bo.toString();
		return xmlStr;
	}

	/**
	 * @description: 对List 中Map 转换成xml字符串
	 * @param list 参数：list列表
	 * @return String
	 * @throws IOException 异常
	 */
	public static String listToXmlString(List<Map> list) throws IOException {
		Document result = new Document();
		Element root = new Element("DATASETS");
		root.setText("");
		if (list != null) {
			for (Map map : list) {
				Set keys = map.keySet();
				Iterator iterator = keys.iterator();
				Element data = new Element("DATASET");
				while (iterator.hasNext()) {
					String key = String.valueOf(iterator.next());
					String value = String.valueOf(map.get(key));
					Element node = new Element(key);
					node.setText(value);
					data.addContent(node);
				}
				root.addContent(data);
			}
		}
		ArrayList arrayList = new ArrayList();
		arrayList.add(root);
		result.setContent(arrayList);
		String resultXML = docToXml(result);
		return resultXML;
	}

	/**
	 * @description: 对List 中Map 转换成json字符串
	 * @param list 参数：MapList
	 * @return String
	 */
	public static String listToJsonString(List<Map> list){
		String resStr;
		StringBuilder jsons;
		StringBuilder json;
		if (list != null) {
			jsons = new StringBuilder();
			jsons.append("{\"list\":[");
			for (Map map : list) {
				Set keys = map.keySet();
				Iterator iterator = keys.iterator();
				json = new StringBuilder("{");
				while (iterator.hasNext()) {
					String key = String.valueOf(iterator.next());
					String value = String.valueOf(map.get(key));
					json.append("\"").append(key).append("\",");
					json.append("\"").append(value).append("\",");

				}
				jsons.append(json.substring(0, json.length() - 1)).append("},");
			}
			resStr = jsons.substring(0, jsons.length() - 1) + "]}";
		} else {
			resStr = "{}";
		}
		return resStr;
	}


	/**
	 * 正则表达式匹配字符串
	 * @param str 参数：字符串
	 * @param reg 参数：正则表达式
	 * @return boolean
	 */
	public static boolean zhengzeMatchStr(String str,String reg){
		Pattern p;
		Matcher m;
		boolean flag;
		p = Pattern.compile(reg);
		m = p.matcher(str);
		flag = m.matches();
		return flag;
	}


	/**
	 * hashmap转字符串
	 * @param map 参数：map
	 * @return string
	 * 结果：key=value,key=value,key=value......
	 */
	public static String hashMapToString(Map map){
		StringBuilder res = new StringBuilder();
		if (!map.isEmpty()){
			Set set = map.entrySet();
			for (Object o : set) {
				res.append(o.toString()).append(",");
			}
			res.deleteCharAt(res.lastIndexOf(","));
		}
		return res.toString();
	}



	public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException {
		List<Map> mapList = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		map.put("name","范占国");
		map.put("age",23);
		map.put("height",173);
		map.put("weight",150);
		map.put("education","undergraduate");
		map.put("occupation","programmer");
		map.put("hobby","basketball");
		mapList.add(map);
		Map<String, Object> map1 = new HashMap<>();
		map1.put("name","王博");
		map1.put("age",22);
		map1.put("height",168);
		map1.put("weight",120);
		map1.put("education","undergraduate");
		map1.put("occupation","programmer");
		map1.put("hobby","game");
		mapList.add(map1);
		Map<String, Object> map2 = new HashMap<>();
		map2.put("name","魏青波");
		map2.put("age",22);
		map2.put("height",170);
		map2.put("weight",125);
		map2.put("education","undergraduate");
		map2.put("occupation","programmer");
		map2.put("hobby","novel");
		mapList.add(map2);
		System.out.println(mapList);
		System.out.println(listToJsonString(mapList));
		System.out.println(listToXmlString(mapList));
	}

}
